#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys
from docx import Document
from docx.table import Table
import json
import re

def analyze_docx_enhanced(file_path):
    """增强的Word文档分析，更准确地识别目标标题和表格"""
    try:
        doc = Document(file_path)
        
        result = {
            "document_info": {
                "total_paragraphs": len(doc.paragraphs),
                "total_tables": len(doc.tables)
            },
            "target_section_analysis": {
                "found": False,
                "paragraph_index": -1,
                "exact_match": False,
                "similar_matches": []
            },
            "table_analysis": {
                "all_tables": [],
                "tables_with_operation_steps": [],
                "main_operation_tables": []
            },
            "data_verification": {
                "expected_pattern_23_33_203": False,
                "actual_row_counts": [],
                "total_data_rows": 0
            }
        }
        
        # 目标标题的不同变体
        target_patterns = [
            "七、启动前有关厂站一、二次设备运行方式调整及状态确认（此项内容表格化）",
            "七、 启动前有关厂站一、二次设备运行方式调整及状态确认（此项内容表格化）",
            "启动前有关厂站一、二次设备运行方式调整及状态确认（此项内容表格化）",
            "启动前有关厂站一、二次设备运行方式调整及状态确认"
        ]
        
        print("=== 增强文档分析 ===")
        print(f"总段落数: {len(doc.paragraphs)}")
        print(f"总表格数: {len(doc.tables)}")
        print()
        
        # 查找目标标题
        target_found = False
        target_paragraph_index = -1
        
        for i, paragraph in enumerate(doc.paragraphs):
            text = paragraph.text.strip()
            if text:
                # 检查是否匹配目标标题
                for pattern in target_patterns:
                    if pattern in text:
                        print(f"[OK] 找到目标标题 (段落 {i}): {text}")
                        result["target_section_analysis"]["found"] = True
                        result["target_section_analysis"]["paragraph_index"] = i
                        result["target_section_analysis"]["exact_match"] = (text == pattern)
                        target_found = True
                        target_paragraph_index = i
                        break
                
                # 记录相似的匹配
                if "启动前" in text and "设备运行方式" in text and "状态确认" in text:
                    result["target_section_analysis"]["similar_matches"].append({
                        "index": i,
                        "text": text
                    })
        
        if not target_found:
            print("[WARNING] 未找到完整的目标标题，但找到相似匹配:")
            for match in result["target_section_analysis"]["similar_matches"]:
                print(f"  段落 {match['index']}: {match['text']}")
        
        print(f"\n=== 详细表格分析 ===")
        
        # 分析所有表格
        operation_tables = []
        
        for table_idx, table in enumerate(doc.tables):
            table_info = {
                "index": table_idx,
                "rows": len(table.rows),
                "columns": len(table.columns) if table.rows else 0,
                "headers": [],
                "is_operation_table": False,
                "has_sequence_numbers": False,
                "step_numbers": [],
                "受令单位_column": -1,
                "操作步骤_column": -1
            }
            
            # 提取表头
            if table.rows:
                header_row = table.rows[0]
                for col_idx, cell in enumerate(header_row.cells):
                    cell_text = cell.text.strip()
                    table_info["headers"].append(cell_text)
                    
                    # 检查是否是操作相关的列
                    if "受令单位" in cell_text:
                        table_info["受令单位_column"] = col_idx
                    if "操作步骤" in cell_text:
                        table_info["操作步骤_column"] = col_idx
                
                # 判断是否是操作表格
                if table_info["受令单位_column"] >= 0 and table_info["操作步骤_column"] >= 0:
                    table_info["is_operation_table"] = True
                    operation_tables.append(table_info)
                
                # 检查序号列
                sequence_numbers = []
                for row_idx in range(1, len(table.rows)):
                    if table.rows[row_idx].cells:
                        first_cell = table.rows[row_idx].cells[0].text.strip()
                        # 尝试提取数字
                        if first_cell.isdigit():
                            sequence_numbers.append(int(first_cell))
                        else:
                            # 尝试从复杂字符串中提取数字
                            numbers = re.findall(r'\d+', first_cell)
                            if numbers:
                                sequence_numbers.append(int(numbers[0]))
                
                if sequence_numbers:
                    table_info["has_sequence_numbers"] = True
                    table_info["step_numbers"] = sequence_numbers
            
            result["table_analysis"]["all_tables"].append(table_info)
            
            print(f"\n表格 {table_idx + 1}:")
            print(f"  行数: {table_info['rows']} (数据行: {table_info['rows']-1 if table_info['rows'] > 0 else 0})")
            print(f"  列数: {table_info['columns']}")
            print(f"  表头: {table_info['headers']}")
            print(f"  是操作表格: {table_info['is_operation_table']}")
            if table_info['has_sequence_numbers']:
                print(f"  序号范围: {min(table_info['step_numbers'])} - {max(table_info['step_numbers'])}")
        
        # 分析操作表格
        if operation_tables:
            print(f"\n=== 操作表格统计 ===")
            print(f"操作表格数量: {len(operation_tables)}")
            
            data_row_counts = []
            for i, table_info in enumerate(operation_tables):
                data_rows = table_info['rows'] - 1  # 减去表头行
                data_row_counts.append(data_rows)
                print(f"  操作表格 {i+1}: {data_rows} 行数据 (总 {table_info['rows']} 行)")
                result["table_analysis"]["tables_with_operation_steps"].append(table_info)
            
            result["data_verification"]["actual_row_counts"] = data_row_counts
            result["data_verification"]["total_data_rows"] = sum(data_row_counts)
            
            # 检查是否符合预期模式
            if len(data_row_counts) >= 3:
                first_three = data_row_counts[:3]
                print(f"\n前三个操作表格的数据行数: {first_three}")
                expected = [23, 33, 203]
                if first_three == expected:
                    print("[OK] 完全符合预期的 23+33+203=259 行数模式")
                    result["data_verification"]["expected_pattern_23_33_203"] = True
                else:
                    print("[ERROR] 不符合预期模式")
                    print(f"  期望: {expected}")
                    print(f"  实际: {first_three}")
                    
                    # 计算总和并检查
                    total_expected = sum(expected)
                    total_actual = sum(first_three)
                    print(f"  期望总数: {total_expected}")
                    print(f"  实际总数: {total_actual}")
            
            print(f"\n所有操作表格总数据行数: {sum(data_row_counts)}")
        
        # 查找主要操作表格（最大的几个表格）
        sorted_tables = sorted(result["table_analysis"]["all_tables"], 
                              key=lambda x: x["rows"], reverse=True)
        
        print(f"\n=== 最大的表格 ===")
        for i, table in enumerate(sorted_tables[:5]):  # 显示前5个最大的表格
            print(f"表格 {table['index']+1}: {table['rows']} 行, {table['columns']} 列")
            if table["is_operation_table"]:
                print(f"  [OPERATION] 操作表格")
        
        return result
        
    except Exception as e:
        print(f"分析文档时出错: {str(e)}")
        import traceback
        traceback.print_exc()
        return {"error": str(e)}

if __name__ == "__main__":
    file_path = "E:/java_projects/ai-doc-portal/test-results/附件2.110kV宝嘉变电站及110kV莲宝线1S1启动方案（例子）.docx"
    
    print("开始增强分析Word文档...")
    result = analyze_docx_enhanced(file_path)
    
    # 保存结果
    output_file = "E:/java_projects/ai-doc-portal/test-results/enhanced_docx_analysis_result.json"
    with open(output_file, 'w', encoding='utf-8') as f:
        json.dump(result, f, ensure_ascii=False, indent=2)
    
    print(f"\n增强分析完成，结果已保存到: {output_file}")